import Web3 from 'web3'
import {store} from '../store/'
let pollWeb3 = function (state) {
    let web3 = window.web3//实例化web3
    web3 = new Web3(web3.currentProvider)
  //设置一个间隔来检查地址是否发生了变化，如果没有，检查余额是否发生了变化
    setInterval(() => {
      if (web3 && store.state.web3.web3Instance) {
        if (web3.eth.coinbase !== store.state.web3.coinbase) {
          let newCoinbase = web3.eth.coinbase
          web3.eth.getBalance(web3.eth.coinbase, function (err, newBalance) {
            if (err) {
              console.log(err)
            } else {
              store.dispatch('pollWeb3', {
                coinbase: newCoinbase,
                balance: parseInt(newBalance, 10)
              })
            }
          })
        } else {
          web3.eth.getBalance(store.state.web3.coinbase, (err, polledBalance) => {
            if (err) {
              console.log(err)
            } else if (parseInt(polledBalance, 10) !== store.state.web3.balance) {
              store.dispatch('pollWeb3', {
                coinbase: store.state.web3.coinbase,
                balance: polledBalance
              })
            }
          })
        }
      }
    }, 500)
  }
  //如果地址或余额有变化，我们将更新我们的 store。因为我们的 hello-metamask 组件具有一个 Computed 属性，这个改变是响应式的
  export default pollWeb3